﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Data.EntityClasses;
using NetDon.OA.Interface;
using NetDon.OA.Interface.CRM;
using NetDon.OA.Interface.Common;
using NetDon.OA.Interface.Configuration;
using NetDon.Utilities;

namespace NetDon.OA.Portal.Shunting
{
    [Navigation("干线流程", "现场装车编辑")]
    public partial class OnsiteEntruckingEdit : NavigationPageBase
    {
        protected Guid Id
        {
            set { ViewState["Id"] = value; }
            get
            {
                if (ViewState["Id"] != null)
                    return ViewState["Id"].ToString().ToGuid();
                return Guid.Empty;
            }
        }

        private bool IsEntrucked { get; set; }

        protected override IList<Guid> Ids
        {
            get
            {
                if (string.IsNullOrWhiteSpace(this.fieldIds.Value))
                    return new List<Guid>();
                return this.fieldIds.Value.Split(new char[] { ',' }).Select(id => id.ToGuid()).ToList();

            }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

        }
        void ClearInitialDropdown()
        {
            this.ddlOnsiteOperator.Items.Clear();

        }
        protected void Page_Load(object sender, EventArgs e)
        {

            txtStartShippmentDateCalendarExtender2.Format = SystemConfiguration.DateFormat;

            this.txtActualEntruckingBoxAmount.Attributes.Add("onchange", "checkActualEntruckingBoxAmount(this);");
            txtActualShippingDate_CalendarExtender1.Format = SystemConfiguration.DateFormat;
            this.txtActualShippingDate.Attributes.Add("onchange", "calculateDelayedDays(this);");
            this.txtGoodsJiltedReasons.Attributes.Add("onchange", "IsGoodsJilted(this);");
            
            if (!IsPostBack)
            {
                CancelButton = btnCancel;

            }
        }

        private void LoadInitialView()
        {
          
            CurrentIndex = -1;
            LoadUserControl(Ids.Count > 0 ? Ids[++CurrentIndex] : Guid.Empty); 
            SetButtonState(Ids.Count <= 0, true, false, Ids.Count == 1);

        }

        public void LoadUserControl(Guid id)
        {
            Id = id;


            var orderService = ServiceContainer.GetService<IIssuingOrderService>();
            var issuingOrderData = orderService.GetIssuingOrder(Id);
            fieldOrderQuantity.Value = issuingOrderData.OrderQuantity.ToString();
            ClearInitialDropdown();
            FormPanelIssuringOrderInfo.DataSource = issuingOrderData;
            FormPanelIssuringOrderInfo.DataBind();

            FormPanelBasicInfo.DataSource = issuingOrderData;
                FormPanelBasicInfo.DataBind();

            var issuingOrderDeliveries = orderService.GetIssuingOrderDeliveryByOrderId(id);
            var gridViewOrderDelivery =
                this.FormPanelIssuingOrderDelivery.FindControl("gridOrderDetailList") as NetDon.WebControls.GridView;
            gridViewOrderDelivery.DataSource = issuingOrderDeliveries;
            gridViewOrderDelivery.DataBind();
            
            ddlOnsiteOperator.SelectedValue = issuingOrderData.OnsiteOperator.HasValue
                                                  ? issuingOrderData.OnsiteOperator.ToString()
                                                  : string.Empty;

            if (string.IsNullOrWhiteSpace(txtStartShippmentDate.Text))
            {
                var issuingOrderVehicleData = orderService.GetIssuingOrderVehicleInfo(id);
                var maxDriverOnboardDate =  issuingOrderVehicleData.Max(o => o.DriverOnboardDate);
                txtStartShippmentDate.Text = maxDriverOnboardDate.HasValue ? maxDriverOnboardDate.Value.Date.ToString("yyyy-MM-dd") : DateTime.Now.ToString("yyyy-MM-dd");
                txtStartShippmentDateHour.Text = maxDriverOnboardDate.HasValue ? maxDriverOnboardDate.Value.Date.ToString("HH") : DateTime.Now.ToString("HH");
            }

           //ddlActualEntruckingUnit.SelectedValue = issuingOrderData.ActualEntruckingUnit.ToString();

            //if(issuingOrderData.PlannedShippingDate.HasValue)
            //{
            //    txtPlannedShippingDate.Value = issuingOrderData.PlannedShippingDate.Value.ToString("yyyy-MM-dd");
            //}
            OrderStatus = issuingOrderData.OrderStatus;
            IsEntrucked = issuingOrderData.OrderStatus == OrderStatus.Entrucked &&
                          !issuingOrderData.ActualShippingDate.HasValue;
            FormPanelIssuringOrderInfo.Enabled = IsEditable();

        }


        protected void gridIssuingOrderDelivery_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //var issuingOrderDeliveryId = (e.Row.DataItem as IssuingOrderDeliveryData).Id.ToString();

                var txtActualEntruckingOrderQuantity = (TextBox)e.Row.FindControl("txtActualEntruckingOrderQuantity");
                var txtOrderQuantity = (Label)e.Row.FindControl("txtOrderQuantity");
                if (string.IsNullOrWhiteSpace(txtActualEntruckingOrderQuantity.Text) || !txtActualEntruckingOrderQuantity.Text.ToDecimal().HasValue || txtActualEntruckingOrderQuantity.Text.ToDecimal().Value == 0m)
                {
                    txtActualEntruckingOrderQuantity.Text = txtOrderQuantity.Text;
                }
                var txtActualEntruckingOrderVolumn = (TextBox)e.Row.FindControl("txtActualEntruckingOrderVolumn");
                var txtOrderVolumn = (Label)e.Row.FindControl("txtOrderVolumn");
                if (string.IsNullOrWhiteSpace(txtActualEntruckingOrderVolumn.Text) || !txtActualEntruckingOrderVolumn.Text.ToDecimal().HasValue || txtActualEntruckingOrderVolumn.Text.ToDecimal().Value == 0m)
                {
                    txtActualEntruckingOrderVolumn.Text = txtOrderVolumn.Text;
                }
                var txtActualEntruckingOrderWeight = (TextBox)e.Row.FindControl("txtActualEntruckingOrderWeight");
                var txtOrderWeight = (Label)e.Row.FindControl("txtOrderWeight");
                if (string.IsNullOrWhiteSpace(txtActualEntruckingOrderWeight.Text) || !txtActualEntruckingOrderWeight.Text.ToDecimal().HasValue || txtActualEntruckingOrderWeight.Text.ToDecimal().Value == 0m)
                {
                    txtActualEntruckingOrderWeight.Text = txtOrderWeight.Text;
                }
                txtActualEntruckingOrderQuantity.Attributes.Remove("onblur");

                txtActualEntruckingOrderQuantity.Attributes.Add("onblur",
                                                    "onChangeQuantity(this,'" + txtOrderQuantity.ClientID +
                                                    "','实际下单数量不可以大于下单数量');return false;");

                txtActualEntruckingOrderVolumn.Attributes.Remove("onblur");

                txtActualEntruckingOrderVolumn.Attributes.Add("onblur",
                                                    "onChangeQuantity(this,'" + txtOrderVolumn.ClientID +
                                                    "','实际下单材积不可以大于下单材积');return false;");

                txtActualEntruckingOrderWeight.Attributes.Remove("onblur");

                txtActualEntruckingOrderWeight.Attributes.Add("onblur",
                                                    "onChangeQuantity(this,'" + txtOrderWeight.ClientID +
                                                    "','实际下单重量不可以大于下单重量');return false;");

            }
        }

        protected override bool IsEditable()
        {
            if (IsManager()) return true;
            return OrderStatus == OrderStatus.Shunted ;
        }



        void SetButtonState(bool isAdd, bool isFirst, bool isLast, bool isSingleEdit)
        {

            SetButtonState(isAdd, isFirst, isLast, isSingleEdit, this.btnSave, btnCancel, btnPrevious, btnNext, btnSaveAndPrevious, btnSaveAndNext, panelBasic);
        }

        public bool SaveOrder()
        {

            DateTime plannedShippingDate = DateTime.MinValue, actualShippingDate = DateTime.MinValue;
            DateTime.TryParse(txtPlannedShippingDate.Text, out plannedShippingDate);
            DateTime.TryParse(txtActualShippingDate.Text, out actualShippingDate);
            if (!string.IsNullOrWhiteSpace(txtPlannedShippingDate.Text) && !string.IsNullOrWhiteSpace(txtActualShippingDate.Text))
            {


                //if (plannedShippingDate > actualShippingDate)
                //{
                //    Alert("实发货日期应该大于等于应发货日期。");
                //    return false;
                //}
            }

            DateTime startShippmentDate = DateTime.MinValue;
            if (!string.IsNullOrWhiteSpace(txtStartShippmentDate.Text))
            {
                if (!DateTime.TryParse(txtStartShippmentDate.Text, out startShippmentDate))
                {
                    //Alert("请输入合法的货物起运时间。");
                    return false;
                }
            }
            int startShippmentDateHour = 0;

            if (!string.IsNullOrWhiteSpace(this.txtStartShippmentDateHour.Text) )
            {
                if (!int.TryParse(this.txtStartShippmentDateHour.Text, out startShippmentDateHour))
                {
                    Alert("请输入正确的货物起运时间小时数。");
                    return false;
                }
            }
            //var actualEntruckingAmount = this.txtActualEntruckingAmount.Text.ToDecimal()??0;
            //if(actualEntruckingAmount <=0)
            //{
            //    Alert("实际装车数量必须大于0");
            //    return false;
            //}
            var service = ServiceContainer.GetService<IIssuingOrderService>();
            var order = service.GetIssuingOrder(Id);


            order.IssuingOrderDeliveryDataList = new List<IssuingOrderDeliveryData>();
            if (actualShippingDate > DateTime.MinValue)
            {
                order.OrderStatus = (int)order.OrderStatus > (int)OrderStatus.Entrucked ? order.OrderStatus : OrderStatus.Entrucked;
                order.ActualShippingDate = actualShippingDate;
            }
            order.DelayedDays = SystemUtility.GetDelayedDays(plannedShippingDate, order.ActualShippingDate);
            order.Id = Id != Guid.Empty ? Id : Guid.NewGuid();
            order.StartShippmentDate = startShippmentDate.AddHours(startShippmentDateHour);
            order.OnsiteOperator = ddlOnsiteOperator.SelectedValue.ToGuid();
            //order.ActualEntruckingAmount = actualEntruckingAmount;
            //order.ActualEntruckingUnit = this.ddlActualEntruckingUnit.SelectedValue.ToInt32()??0;
            order.ActualEntruckingBoxAmount = this.txtActualEntruckingBoxAmount.Text.ToInt32()??0;
            order.GoodsJiltedReasons = this.txtGoodsJiltedReasons.Text.Trim();
            order.IsGoodsJilted = !string.IsNullOrWhiteSpace(this.txtGoodsJiltedReasons.Text.Trim());
            order.OnsiteEntruckingComments = this.txtOnsiteEntruckingComments.Text.Trim();
            order.GoodsLeftBoxAmount = (int)SystemUtility.GetGoodsLeftAmount(order.OrderQuantity,
                                                                        order.ActualEntruckingBoxAmount);
            order.DelayedReasons = txtDelayedReasons.Text.Trim();
            order.LastUpdatedBy = CurrentApplicationContext.UserId;
            order.LastUpdatedDate = DateTime.Now;
            order.IssuingOrderDeliveryDataList = ExtractIssuingOrderDelivery();
            bool result = false;
            result = Id != Guid.Empty ? service.ModifyOrder(order) : service.AddOrder(order);
            if (result)
                Success("保存成功!");
            return result;


        }

        private IList<IssuingOrderDeliveryData> ExtractIssuingOrderDelivery()
        {
            var tempIssuingOrderDeliveries = new List<IssuingOrderDeliveryData>();
            foreach (GridViewRow detailRow in gridOrderDetailList.Rows)
            {
                var issuingOrderDeliveryId = gridOrderDetailList.DataKeys[detailRow.RowIndex]["Id"].ToString().ToGuid();
                var issuingOrderDelivery =
                    ServiceContainer.GetService<IIssuingOrderService>().GetIssuingOrderDelivery(issuingOrderDeliveryId);

                if (issuingOrderDelivery != null)
                {


                    issuingOrderDelivery.ActualEntruckingOrderQuantity = (detailRow.FindControl("txtActualEntruckingOrderQuantity") as TextBox).Text.ToDecimal();
                    issuingOrderDelivery.ActualEntruckingOrderVolumn = (detailRow.FindControl("txtActualEntruckingOrderVolumn") as TextBox).Text.ToDecimal() ;
                    issuingOrderDelivery.ActualEntruckingOrderWeight = (detailRow.FindControl("txtActualEntruckingOrderWeight") as TextBox).Text.ToDecimal() ;
  
                    issuingOrderDelivery.LastUpdatedBy = CurrentApplicationContext.UserId;
                    issuingOrderDelivery.LastUpdatedDate = DateTime.Now;
                    tempIssuingOrderDeliveries.Add(issuingOrderDelivery);
                }

            }

            return  tempIssuingOrderDeliveries;
        }

        protected void btnReLoadIds_Click(object sender, EventArgs e)
        {
            LoadInitialView();
            btnReLoadIds.Enabled = false;
        }


        protected void btnSaveAndNext_Click(object sender, EventArgs e)
        {
            if (SaveOrder())
            {

                btnNext_Click(sender, e);

            }
        }
        protected void btnSaveAndPrevious_Click(object sender, EventArgs e)
        {
            if (SaveOrder())
            {

                btnPrevious_Click(sender, e);

            }
        }
        protected void btnNext_Click(object sender, EventArgs e)
        {

            if (HasNextView())
            {
                LoadNavigationView(Ids[++CurrentIndex]);
            }

            SetButtonState(false, IsFirstView, IsLastView, false);



        }
        protected void btnPrevious_Click(object sender, EventArgs e)
        {
            if (HasPreviousView())
            {
                LoadNavigationView(Ids[--CurrentIndex]);

            }
            SetButtonState(false, IsFirstView, IsLastView, false);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (SaveOrder())
            {
                CloseWindow(true);
            }

        }




        internal void LoadNavigationView(Guid id)
        {

            Id = id;

            LoadUserControl(id);

        }


    }
}